import axios from 'axios'
import store from '@/store'
import { Message } from 'element-ui'
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API,
  timeout: 5000
})

service.interceptors.request.use(
  (config) => {
    // if (store.state.user.token.length) {
    //   config.headers.Authorization = `Bearer ${store.state.user.token}`
    // }
    const token = store.getters.token
    if (token) {
      config.headers.Authorization = `Bearer ${token}`
    }
    return config
  },
  (error) => {
    return Promise.reject(error)
  }
)

service.interceptors.response.use(
  (response) => {
    const { success, message } = response.data
    if (success) return response.data
    else {
      Message.error(message)
      return Promise.reject(message)
    }
  },
  (error) => {
    Message.error(error.response.data.message)
    console.dir(error)
    // if (error.response.status === 401)
    // if (error && error.response && error.response.data && error.response.data.code === 10002)
    if (error?.response?.data?.code === 10002) {
      // store.commit('user/REMOVE_TOKEN')
      // router.replace('/login')
      store.dispatch('user/logOutActions')
    }
    return Promise.reject(error)
  }
)

export default service
